package comp302.prototype.xml;

import java.util.ArrayList;
import java.util.Iterator;

public class XMLNode {

	private String name = "", value = "";
	private ArrayList<XMLAttribute> attributes = new ArrayList<XMLAttribute>();
	private ArrayList<XMLNode> children = new ArrayList<XMLNode>();

	public XMLNode(String name) {
		this.name = name;
	}

	public XMLNode(String name, String value) {
		this.name = name;
		this.value = value;
	}
	
	public String getName() {
		return name;
	}
	
	public String getValue() {
		return value;
	}

	public void setAttribute(String name, String value) {
		Iterator<XMLAttribute> iterator = attributes.iterator();

		while (iterator.hasNext()) {
			XMLAttribute attr = iterator.next();

			if (attr.getName().equalsIgnoreCase(name)) {
				attr.setValue(value);
				return;
			}
		}

		attributes.add(new XMLAttribute(name, value));
	}
	
	public String getAttribute(String attribute) {
		Iterator<XMLAttribute> iterator = attributes.iterator();

		while (iterator.hasNext()) {
			XMLAttribute attr = iterator.next();

			if (attr.getName().equalsIgnoreCase(attribute)) {
				return attr.getValue();
			}
		}
		
		return "";
	}

	public void addChild(XMLNode child) {
		if (child != null) {
			children.add(child);
		}
	}

	public XMLNode getChild(int index) {
		return children.get(index);
	}

	public Iterator<XMLAttribute> attributeIterator() {
		return attributes.iterator();
	}

	public Iterator<XMLNode> childIterator() {
		return children.iterator();
	}

	public String toString() {
		String xml = "<" + name;
		Iterator<XMLAttribute> aiter = attributes.iterator();
		Iterator<XMLNode> citer = children.iterator();

		while (aiter.hasNext()) {
			xml += " " + aiter.next();
		}

		xml += ">" + value;

		while (citer.hasNext()) {
			xml += citer.next();
		}

		xml += "</" + name + ">";
		return xml;
	}
}
